package edu.stanford.prpl.android;

import android.app.Activity;
import android.app.ProgressDialog;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.content.Intent;
import android.content.res.Resources;
import java.io.*;
import java.net.*;
import java.lang.Runnable;
import java.util.HashMap;

import edu.stanford.prpl.facade.*;
import edu.stanford.prpl.facade.android.*;

public class AppActivity extends Activity implements Runnable, FacadeAndroidData
{
	private static final String TAG = "FacadeAndroid AppActivity";
	public  static UIEngine androidUI_engine = null;
	private static View currentUI = null;
	private static AppActivity currentAppActivity = null;


	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        
        Log.d(TAG, "App Activity starting... \n");
        String outputString = "Facade for Android";
        
        // Retrieve PageTitle and ActionCall from bundle
        Intent i = getIntent();
        String pageTitle  = i.getStringExtra("pageTitle");
        String actionCall = i.getStringExtra("actionCall");
        
        //if (AppActivity.androidUI_engine == null)
        //	AppActivity.androidUI_engine = FacadeAndroid.android_facade_ui_engine;
        
        if (currentUI == null)
        {
            Object UIresult = null;
            try
            {
            	// Input data, Output UI
            	String dataXML_url = actionCall;
            	URL data_xml = new URL(dataXML_url);
            	BufferedReader in = new BufferedReader(
                                    	new InputStreamReader(data_xml.openStream())
                                	);
            	
            	Log.d(TAG, "Opening URL: "+dataXML_url);

            	UIresult = AppActivity.androidUI_engine.render(in, pageTitle, UIEngine.renderType.NORMAL, this);        	
            	in.close();
            }
            catch (Exception e)
            {
            	outputString = "\n\nException: "+e.toString()+" \n";
            }
            
        	if (UIresult instanceof View)
        	{
        		setContentView((View)UIresult);
        		Log.d(TAG, "\n\nInitial UI Facade Activated!!! \n");
        	}
        	else
        	{
            	if (UIresult == null)
            		outputString = "\n\nUI Result is NULL! For url:\n"+actionCall;
        		
            	// UI
            	setContentView(R.layout.main);
            	TextView mIntroMessage = (TextView)findViewById(R.id.intro_message);
            	mIntroMessage.setText(outputString);
        	}        	
            	
        }
        else
        {
        	setContentView(currentUI);
    		Log.d(TAG, "\n\nGenerated UI Facade Activated!!! \n");
        }
    }

    
    @Override
    public void onResume() 
    {
    	AppActivity.currentAppActivity = this;
    	super.onResume();   	
    }

    
    public OnClickListener getAppClickResponse()
    {
    	return mClickEvent;
    }
    
    public OnItemClickListener getAppListItemClickResponse()
    {
    	return mListItemClickEvent;
    }

	// View.OnClickListener
    public static OnClickListener mClickEvent = new OnClickListener()
    {
		public void onClick(View v)
		{
			HashMap<String, Object> actionBundle = (HashMap<String, Object>)v.getTag();
			// Intent i = getIntent();

        	String pageTitle = (String)actionBundle.get("pageTitle");
        	String actionCall = (String)actionBundle.get("actionCall");
			
			Intent chosen = new Intent();
			chosen.setData(Uri.parse(actionCall));
			if (pageTitle != null)
			   chosen.putExtra("pageTitle", pageTitle);
			if (actionCall != null)
			   chosen.putExtra("actionCall", actionCall);
			
			Log.d("AppActivity.OnClickListener", "pageTitle: " +pageTitle);
			Log.d("AppActivity.OnClickListener", "actionCall: "+actionCall);

			// chosen.setAction(Intent.ACTION_VIEW);
			// chosen.setClass(AppActivity.this, AppActivity.class);
			// startActivity(chosen);
		}
    };    
    
    
	private static HashMap<String, Object> m_ActionBundle = null;
	private static ProgressDialog m_ProgressDialog = null;
	
    
	// AdapterView.OnItemClickListener
    public static OnItemClickListener mListItemClickEvent = new OnItemClickListener()
    {
		public void onItemClick(AdapterView<?> adapter, View v, int pos, long id)
		{
			String pageTitle = null, action = null, actionCall = null;
			
			/* Clicked on a separator row. */
			if (id == -1)
				return;

			m_ActionBundle = (HashMap<String, Object>)v.getTag();
			// Intent i = getIntent();
			
			if (m_ActionBundle != null)
			{
				pageTitle = (String)m_ActionBundle.get("pageTitle");
				action = (String)m_ActionBundle.get("action");
				actionCall = (String)m_ActionBundle.get("actionCall");
			}
			else
				return;

        	// if (actionCall == null || actionCall.trim().length() <= 0)
        	//	  return;

			if (AppActivity.currentAppActivity != null)
			{
			   // Display In-Progress message
			   m_ProgressDialog = ProgressDialog.show(AppActivity.currentAppActivity, "Please wait...",
					                                  "Retrieving "+pageTitle+" ...", true);
			
			   // Do XML data parsing and UI generation work in another thread
	           Thread thread =  new Thread(null, AppActivity.currentAppActivity, "NextPageUIGeneration");
	           thread.start();
			}
		}
    };

    
    public void run()
    {
		String pageTitle = null, action = null, actionCall = null;
		
		if (m_ActionBundle != null)
		{
			pageTitle = (String)this.m_ActionBundle.get("pageTitle");
			action = (String)this.m_ActionBundle.get("action");
			actionCall = (String)this.m_ActionBundle.get("actionCall");
		}
	
		// Generate UI
		String outputString = "Facade for Android";
        Object UIresult = null;
        try
        {
        	// Input data, Output UI
        	String dataXML_url = actionCall;
        	URL data_xml = new URL(dataXML_url);
        	BufferedReader in = new BufferedReader(
                                	new InputStreamReader(data_xml.openStream())
                            	);
        	
        	System.out.println("AppActivity.OnItemClickListener: Opening URL: "+dataXML_url);

        	UIresult = AppActivity.androidUI_engine.render(in, pageTitle, UIEngine.renderType.NORMAL, this);        	
        	in.close();
        }
        catch (Exception e)
        {
        	outputString = "\n\nException: "+e.toString()+" \n";
        }
        
    	if (UIresult instanceof View)
    	{
    		AppActivity.currentUI = (View)UIresult;
    		// Log.d("AppActivity.OnItemClickListener", "\n\nUI Facade generated!!! \n");
    	}
    	else
    	{
        	if (UIresult == null)
        		outputString = "\n\nUI Result is NULL! For url:\n"+actionCall;
    		
            // Build Android native UI
        	LayoutInflater mInflater = LayoutInflater.from(this);
            View plainPageUI = (View)mInflater.inflate(R.layout.main,
            									       null, false);
        	TextView mIntroMessage = (TextView)plainPageUI.findViewById(R.id.intro_message);
        	mIntroMessage.setText(outputString);
        	
        	AppActivity.currentUI = plainPageUI;
    	}
    	
    	
    	runOnUiThread(showNewListPage);  
    }


    private Runnable showNewListPage = new Runnable() 
    {
        public void run() 
        {
        	String pageTitle = null, action = null, actionCall = null;
        	
        	// Remove In-Progress message
        	m_ProgressDialog.dismiss();
        	
        	if (m_ActionBundle != null)
    		{
    			pageTitle = (String)m_ActionBundle.get("pageTitle");
    			action = (String)m_ActionBundle.get("action");
    			actionCall = (String)m_ActionBundle.get("actionCall");
    		}
        	
        	// Invoke new Android UI Page/Activity
    		Intent chosen = new Intent();
    		chosen.setData(Uri.parse(actionCall));
    		if (pageTitle != null)
    		   chosen.putExtra("pageTitle", pageTitle);
    		if (actionCall != null)
    		   chosen.putExtra("actionCall", actionCall);
    		
    		System.out.println("showNewListPage: pageTitle: " +pageTitle);
    		System.out.println("showNewListPage: actionCall: "+actionCall);

    		chosen.setAction(Intent.ACTION_VIEW);
    		chosen.setClass(AppActivity.this, AppActivity.class);
    		startActivity(chosen);
        }
    };      

    	
}